//
//  PYShowMediaDismissAnimation.m
//  IHome
//
//   Created by zhujizheng on 2020/2/18.
//  Copyright © 2019年 com.zhujizheng. All rights reserved.
//

#import "PYShowMediaDismissAnimation.h"
#import "PYShowMediaController.h"
#import <AVFoundation/AVFoundation.h>
#import "PYMediaInfo.h"

@implementation PYShowMediaDismissAnimation
// 返回动画的时间
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext{
    return PY_Animation_Duration;
}
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext{
    PYShowMediaController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView * container = [transitionContext containerView];
    UIView *fromView;
    UIView *toView;
    
    if ([transitionContext respondsToSelector:@selector(viewForKey:)]) {
        fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
        toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    } else {
        fromView = fromVC.view;
        toView = toVC.view;
    }
    
    UIView *bgView = [UIView new];
    bgView.frame = CGRectMake(0, 0, APP_WIDTH, APP_HEIGHT);
    bgView.backgroundColor = [UIColor blackColor];
    [[UIApplication sharedApplication].keyWindow addSubview:bgView];
    
    UIImageView *imgView = [UIImageView new];
    imgView.contentMode = UIViewContentModeScaleAspectFill;
    imgView.layer.masksToBounds = YES;
    imgView.image = [fromVC getCurrentImage];
    CGRect frame = CGRectMake(0, 0, APP_WIDTH, APP_HEIGHT);
    if (imgView.image.size.width != 0 && imgView.image.size.height != 0) {
        frame = AVMakeRectWithAspectRatioInsideRect(imgView.image.size, CGRectMake(0, 0, APP_WIDTH, APP_HEIGHT));
    }
    imgView.frame = frame;
    [[UIApplication sharedApplication].keyWindow addSubview:imgView];
    
    [fromView removeAllSubviews];
    [container addSubview:toView];
    
    [UIView animateKeyframesWithDuration:[self transitionDuration:transitionContext] delay:0 options:2 animations:^{
        PYMediaInfo *mediaInfo = [fromVC getCurrentModel];
        if (mediaInfo) {
            imgView.frame = mediaInfo.imgViewFrame;
            imgView.layer.cornerRadius = mediaInfo.imgViewCornerRadius;
        }
        bgView.alpha = 0;
    } completion:^(BOOL finished) {
        if (finished) {
            [bgView removeAllSubviews];
            [imgView removeFromSuperview];
            
            BOOL wasCancelled = [transitionContext transitionWasCancelled];
            if (wasCancelled) {
                [toView removeFromSuperview];
            }
            [transitionContext completeTransition:!wasCancelled];
        }
    }];
}
@end
